package com.huike.controller;

import java.util.Date;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huike.utils.JsonUtilsForRichText;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.huike.entity.Information;
import com.huike.service.IInformationService;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Lwen
 * @since 2019-11-12
 */
@RestController
@RequestMapping("/information")
public class InformationController {

	@Autowired
	IInformationService iInformationService;

	/**
	 * 获取所有最新资讯新闻的所有信息，并展示在首页
	 * 
	 * @return
	 */
	@RequestMapping("/getInformationAction")
	@ResponseBody
	public List<Information> getInformationAction() {
		List<Information> informations = iInformationService.list();
		Collections.sort(informations, new Comparator<Information>() { // 按照时间逆序排序
			@Override
			public int compare(Information o1, Information o2) {
				// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd
				// HH:mm:ss");
				try {
					Date dt1 = o1.getTime();
					Date dt2 = o2.getTime();
					if (dt1.getTime() > dt2.getTime()) {
						return -1;
					} else if (dt1.getTime() < dt2.getTime()) {
						return 1;
					} else {
						return 0;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return 0;
			}
		});
		// Collections.reverse(informations); //逆序list
		int fromIndex = 0;
		int toIndex = 3;
		if (informations.size() < 3) {
			toIndex = informations.size();
		}
		return informations.subList(fromIndex, toIndex); // 截取前三个数据
	}

	/**
	 * 根据id从数据库里面获取最新资讯新闻的准确信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/getInformationDetail")
	@ResponseBody
	public Information getInformationDetail(String id) {
		Information information = iInformationService.getById(id);
		return information;
	}

	/**
	 * 分页展示infomation
	 * s
	 * @param page
	 * @param limits
	 */
	@RequestMapping("/listInfomationByPage")
	@ResponseBody
	public void listInfomationByPage(HttpServletResponse response, int page, int limits) {
		IPage<Information> iPage = iInformationService.listByPage(page, limits);
		Map<String, Object> map = new HashMap<>();
		map.put("code", 0);
		map.put("total", iPage.getTotal());
		map.put("data", iPage.getRecords());
		JsonUtilsForRichText.jsonArray(map, response);
	}

}
